import 'package:flutter/material.dart';

class GridViewByListViewExample extends StatelessWidget {
  const GridViewByListViewExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GridViewByListViewExample'),
      ),
      body: buildExample(),
    );
  }
}

Widget buildExample() {
  return ListGridView(
    itemBuilder: (BuildContext context, int index) {
      return Container(
        decoration: BoxDecoration(
          border: Border.all(
            width: 1,
            color: Colors.grey,
          ),
        ),
        alignment: Alignment.topLeft,
        child: ListTile(
          title: Text("$index${"你好" * index}"),
        ),
      );
    },
    itemCount: 29,
    perRowCount: 3,
  );
}

class ListGridView extends StatelessWidget {
  final IndexedWidgetBuilder itemBuilder;
  final int itemCount;
  final int perRowCount;

  const ListGridView({
    super.key,
    required this.itemBuilder,
    required this.itemCount,
    this.perRowCount = 1,
  });

  int get rowCount {
    final rows = itemCount ~/ perRowCount;
    if (itemCount % perRowCount != 0) {
      return rows + 1;
    }
    return rows;
  }

  Widget _buildGridWidget(BuildContext context, int index) {
    if (index >= itemCount) {
      return Expanded(child: Container());
    }
    return Expanded(
      child: itemBuilder(context, index),
    );
  }

  Widget _buildRow(BuildContext context, int start, int end) {
    List<Widget> children = [];

    for (var i = start; i < end; i++) {
      children.add(_buildGridWidget(context, i));
    }

    return Row(
      children: children,
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: _buildItem,
      itemCount: rowCount,
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    int start = index * perRowCount;
    int end = start + perRowCount;
    return _buildRow(context, start, end);
  }
}
